import axios from "axios";
import store from "@/store";
import router from "@/router";

import { Toast } from "vant";

// 创建axios实例
const conf = {
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 90000, // 请求超时时间
  withCredentials:true
};

const service = axios.create(conf);

// request拦截器
service.interceptors.request.use(
  config => {
    let token = localStorage.getItem('token');
    if (token) {
      config.headers['token'] = token; // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config;
  },
  error => {
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  }
);

// respone拦截器
service.interceptors.response.use(
  response => {

    const res = response.data;

    if(response.config.responseType === "blob" || response.config.responseType === "arraybuffer") {
      return response;
    } else {
      if(res){
        //校验token失效
        if(res.errorcode == 2001){
          store.dispatch('handleLogout');
          router.replace('/login');
        }else{
          return res;
        }
      }else{
        return Promise.reject(new Error("Error"));
      }        
    }
  },
  error => {
    if (
      error.response &&
      error.response.status &&
      error.response.status === 401
    ) {
      Toast(error.message)
    } else {
      Toast(error.message)
    }
    console.log("err" + error); // for debug
    return Promise.reject(error);
  }
);

export default service;
export { conf };
